local ROT = require 'rot'

local state = ROT.Class:extend()

function state:init(game, play)
    self.game = game
    self.play = play
    self.selected = {}
end

local FIRST_KEY = ('a'):byte() - 1
local DIM = { 120, 120, 120 }
local BRIGHT = { 240, 240, 240 }

function state:update()
    local player = self.game.player
    local stuff = player.stuff
    local display = self.game.display
    display:clear()
    display:write('Equip items:', 1, 1)

    local j = 0
    for i = 1, #stuff do
        if stuff[i].slot and player[stuff[i].slot] ~= stuff[i] then
            j = j + 1
            display:write(
                string.char(
                i + FIRST_KEY) .. ') ' .. stuff[i].name,
                1, 2 + j,
                self.selected[i] and BRIGHT or DIM)
        end
    end

    display:write('Current equipment:', 40, 1)

    display:write('Weapon:', 40, 3)
    display:write(player.weapon.name, 50, 3,
        player.weapon and player.weapon.color or DIM)

    display:write('Armor:', 40, 4)
    display:write(player.armor and player.armor.name or 'nothing', 50, 4,
        player.armor and player.armor.color or DIM)

    local s = '(a-z selects, [esc] cancels, [enter] confirms)'
    display:write(s, display:getWidth() - #s, display:getHeight())

end

function state:keypressed(key)
    local game = self.game
    local player = self.game.player
    local stuff = player.stuff
    if key == '\27' then
        game:popState()
    elseif key == '\n' then
        for i = #player.stuff, 1, -1 do
            if self.selected[i] then
                local equipped = player[stuff[i].slot]
                if equipped then
                    game:log('You lower your ', equipped.name, '.')
                    game.scene:passTime(equipped.heft or 5)
                end
                game:log('You equip the ', stuff[i].name, '.')
                game.scene:passTime(stuff[i].heft or 5)
                player[stuff[i].slot] = stuff[i]
            end
        end
        game:popState()
    else
        local index = key:byte() - FIRST_KEY
        if stuff[index] and stuff[index].slot then
            for i = 1, #stuff do
                if index ~= i and stuff[index].slot == stuff[i].slot then
                    self.selected[i] = false
                end
            end
            self.selected[index] = not self.selected[index]
        end
    end
end

return state
